﻿Imports System.IO
Imports System.Deployment.Application
Imports Microsoft.SqlServer.Server
Imports System.Net
Imports System.Globalization


Public Class frm_display
    Public LogFile As String = "log.txt"

    Public ShopName, ShopCode As String
    Public MyDate As String
    Public LstRecord As List(Of Record) = New List(Of Record)()
    Public TimeSche As TimeSchedule = New TimeSchedule()
    Public Plan As Integer = 0
    Public Actual As Integer = 0
    Public Diff As Integer = 0
    Public Status As String = ""
    Public DuringTime As Integer = 0

    Public LstItem As List(Of Item) = New List(Of Item)()
    'to save list of item at begining of day => count plan
    Public LstTargetToday As List(Of Item) = New List(Of Item)()
    Public IsNewDate As Boolean = True

    'to save the time of model which is manufaturing
    Public ActualTime As Integer = -1
    Public LstActualItem As List(Of ActualItem) = New List(Of ActualItem)()
    Public HasPendingItem As Boolean

    Public WithEvents Tcp As TCPChat = New TCPChat()
    Public HostAddr As String
    Public HostPort As Integer
    Public RemoteAddr As String
    Public RemotePort As Integer

    Public RetryEverySec As Integer
    Public nRetries As Integer
    Public DebugMode As Integer
    Public ActivelySend As Boolean 'if true: when click +1-> send to host, else only wait for host asking and answer
    Public GetPendingPrevDay As Boolean
    Public TimeSpareFromYesterday As Integer
    Public Time2FinishTodayPlan As Integer

    'count how many sending msg to host (for 1 msg)
    Public CountTimesSendingMsg As Integer = 0

    Private prevClick As DateTime = Now


    Private Sub frm_display_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'My.Computer.Audio.Play("ding.wav", AudioPlayMode.Background)
        'delete old schedule files
        DeteleAllOldFiles()

        ''check for connection
        'If Not My.Computer.Network.IsAvailable Then
        '    MessageBox.Show("No connection. Please check and try again!")
        '    Exit Sub
        'End If

        'init log file name, by ww
        Dim dfi = DateTimeFormatInfo.CurrentInfo
        Dim calendar = dfi.Calendar
        Dim weekOfyear = calendar.GetWeekOfYear(Now, dfi.CalendarWeekRule, DayOfWeek.Sunday)
        LogFile = "log_" & weekOfyear.ToString("00") & ".txt"


        lblDate.Text = Today

        GetConfigFile()
        GetRemainTime()

        RichTextBox1.Visible = (DebugMode = 1)
        RichTextBox2.Visible = (DebugMode = 1)
        RichTextBox3.Visible = (DebugMode = 1)
        lblStatus.Visible = (DebugMode = 1)

        'create list item
        AddPendingToLstItem() 'check pending to see if start of the day, or in the middle of the day

        'if IsNewDate, at beginning day
        If IsNewDate Then
            GetSchedule()
            AddScheduleToLstItem()
            SaveTargetToday()

            '-----20141203 Add-----
            CloneLstTargetToLstActualItem()
            SavePendingFile()
            '-----END 20141203 Add-----

            'AddTargetToLstTarget()
            ResetStatusAndNumber()

        Else
            'if power-off
            AddTargetFromFileToLstTarget()
            CloneLstTargetToLstItem()
            '-----20141203 Add-----
            AddPendingToLstActual()
            '-----END 20141203 Add-----
            'Status = GetStatus()
        End If

        GetTimerFile()
        GetNumberFile()
        Status = GetStatusNow()

        '-----20141127-----
        UpdateLstItemAfterCountingPlan()
        '-----END 20141127-----

        '-----20141203 Add-----
        'CloneLstTargetToLstActualItem()
        '-----20141203 Add-----


        'Plan = CountPlan()

        SetInitLabel()
        Timer1.Enabled = True
        Timer1.Interval = 5000 'change on 20141130: from 60s to 5s

        TimerActual.Interval = 60000

        TimerSendMsg.Interval = RetryEverySec * 1000

        If CountWorkingTimeTo(Now.ToString("HH:mm")) > 0 Then
            TimerActual.Enabled = True
            'else when begining working, TimerActual will be enable
        End If

        'If HasPendingItem Then
        '    Dim line = GetLastModelAndTime()
        '    Dim sActualTime = line.Split("|")(1)
        '    ActualTime = CInt(sActualTime)
        'Else
        '    ActualTime = -1
        'End If


        'lblStatus.Text = CountWorkingTimeToNow().ToString()

        ConnetTCP()
        '-------------------------------------

        'Dim da As DateTime = DateTime.Now
        'Dim asd As String = ConvertTimeToString(da)

        'lblStatus.Text = da.ToString("MM/dd/yyyy").Replace("/", "")
        'lblStatus.Text = da.ToString("HH:mm")

        'Dim time As Integer = 0
        'Dim starTime As DateTime = DateTime.ParseExact("07:30", "HH:mm", Nothing)
        'Dim endTime As DateTime = DateTime.ParseExact("06:00", "HH:mm", Nothing)
        'Dim timeSpan As TimeSpan = endTime - starTime
        'time = CInt(timeSpan.TotalMinutes)
        'lblStatus.Text = time


        Dim test As String
        'Dim a As String = "21:00"
        'Dim b As String = "10:30"
        'lblStatus.Text = a.CompareTo(b).ToString()

        'lblStatus.Text = CountWorkingTimeToNow()

        'test = "SCHE|11232014|ABC|2|3|5|ZXC|4|2|1"
        'SaveScheMsg(test)
        'test = "ASKS|11202014"
        'ReplyAskSchedule(test)

        WriteLstItem()
        WriteLstTarget()
        WriteLstActual()

        ' MessageBox.Show(CountWorkingTimeTo("17:05"))
    End Sub

    Public Sub GetConfigFile()
        Try
            Using sr As New StreamReader("ClientSetting.ini")
                Dim line As String

                line = sr.ReadLine()
                ShopName = line.Split("|")(0)
                ShopCode = line.Split("|")(1)

                line = sr.ReadLine().Replace(" ", "").Replace("ThisIP=", "")
                HostAddr = line.Split("|")(0)
                HostPort = line.Split("|")(1)

                line = sr.ReadLine().Replace(" ", "").Replace("HostIP=", "")
                RemoteAddr = line.Split("|")(0)
                RemotePort = line.Split("|")(1)

                nRetries = sr.ReadLine().Replace(" ", "").Replace("nRetries=", "")
                RetryEverySec = sr.ReadLine().Replace(" ", "").Replace("RetryEverySec=", "")
                DebugMode = sr.ReadLine().Replace(" ", "").Replace("DebugMode=", "")
                ActivelySend = (sr.ReadLine().Replace(" ", "").Replace("ActivelySend=", "").Equals("1"))
                GetPendingPrevDay = False
            End Using
        Catch e As Exception
            'MessageBox.Show("'ClientSetting.ini' could not be read!")
            WriteToLog("'ClientSetting.ini' could not be read!")
        End Try
    End Sub

    Public Sub GetNumberFile()
        Try
            Using sr As New StreamReader("number.txt")
                Dim dateInFile As String = sr.ReadLine()
                Dim today As String = DateTime.Now.ToString("MM/dd/yyyy")

                If today.Equals(dateInFile) Then
                    Dim line As String

                    'do nothing with plan no in file. plan no must be counted again
                    line = sr.ReadLine()
                    Plan = CountPlan()

                    line = sr.ReadLine()
                    Actual = Integer.Parse(line)

                    'do nothing with diff no in file. diff no must be counted again
                    line = sr.ReadLine()
                    Diff = Actual - Plan
                Else
                    Plan = 0
                    Actual = 0
                    Diff = 0
                End If
            End Using
        Catch e As Exception
            'MessageBox.Show("'number.txt' could not be read!")
            WriteToLog("'number.txt' could not be read!")
        End Try
    End Sub

    Public Sub SaveNumberFile()
        Try
            Dim file As New StreamWriter("number.txt")
            file.WriteLine(DateTime.Now.ToString("MM/dd/yyyy"))
            file.WriteLine(Plan.ToString())
            file.WriteLine(Actual.ToString())
            file.WriteLine(Diff.ToString())
            file.Close()
        Catch e As Exception
            'MessageBox.Show("Cannot save to 'number.txt'!")
            WriteToLog("Cannot save to 'number.txt'!")
        End Try
    End Sub

    Public Sub ResetStatusAndNumber()
        Status = ""
        SaveStatus(Status)
        Plan = 0
        Actual = 0
        Diff = 0
        SaveNumberFile()
    End Sub

    Public Sub GetSchedule()
        Time2FinishTodayPlan = 0
        Dim strToday As String = DateTime.Now.ToString("yyyyMMdd")
        Dim path As String = "schedule\schedule_" + strToday + ".txt"
        Dim lastTime2Change As Integer = 0
        Try
            Using sr As New StreamReader(path)
                MyDate = sr.ReadLine()
                Dim line As String
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                    'Dim split As String() = line.Split(New [Char]() {"|"c, CChar(vbTab) })
                    Dim split As String() = line.Split("|")
                    Dim record As Record = New Record()
                    record.Model = split(0)
                    record.Volumn = split(1)
                    record.TimeToChange = split(2)
                    record.Duration = split(3)
                    LstRecord.Add(record)

                    Time2FinishTodayPlan += record.Volumn * record.Duration + record.TimeToChange
                    lastTime2Change = record.TimeToChange
                End While
            End Using

            Time2FinishTodayPlan -= lastTime2Change
        Catch e As Exception
            MessageBox.Show("The schedule file could not be read!")
            WriteToLog("The schedule file could not be read!")
        End Try

        '----------20141207 Add by Dung--------
        Dim fW As StreamWriter = New StreamWriter("production.txt")
        fW.WriteLine(Today.ToString("MM/dd/yyyy"))
        fW.Close()
        '----------20141207 END---------
    End Sub

    Private Sub GetRemainTime()
        Try
            Dim fR As StreamReader = New StreamReader("remain.txt")
            Dim i As Integer

            If (Today.Day = 1) Then
                TimeSpareFromYesterday = 0
            Else
                For i = 1 To Today.Day - 2
                    fR.ReadLine()
                Next
                TimeSpareFromYesterday = fR.ReadLine
            End If

            fR.Close()
        Catch ex As Exception
            WriteToLog(ex.Message)
            TimeSpareFromYesterday = 0
        End Try

    End Sub

    Public Function CountTarget() As Integer
        Dim totalUnit As Integer = 0
        For Each record As Record In LstRecord
            totalUnit += record.Volumn
        Next
        Return totalUnit
    End Function

    Public Sub AddScheduleToLstItem()
        'compare last model in pending list and first model in schedule
        'if different, add 1 item has duration = time to change of last item in pending list
        If LstItem.Count > 0 AndAlso LstRecord.Count > 0 Then
            Dim lastModel As String = LstItem(LstItem.Count - 1).Model
            If (Not lastModel.Equals(LstRecord(0).Model)) AndAlso (Not lastModel.Equals("change")) Then
                LstItem.Add(New Item("change", LstItem(LstItem.Count - 1).TimeToChange, LstItem(LstItem.Count - 1).TimeToChange))
            End If
        End If

        Dim firstRecord As Boolean = True

        For Each record As Record In LstRecord
            If firstRecord Then
                'for 1st time, minus the TimeSpareFromYesterday
                If TimeSpareFromYesterday < 0 Then 'this car was in yesterday schedule, and half-done yesterday
                    LstItem.Add(New Item(record.Model, -TimeSpareFromYesterday, record.TimeToChange)) 'actually not this car, but the last car from yesterday schedule

                    For i As Integer = 0 To record.Volumn - 1 'add all, this starts from 0
                        LstItem.Add(New Item(record.Model, record.Duration, record.TimeToChange))
                    Next
                Else
                    'If TimeSpareFromYesterday > 0, meaning there x min from yesterday, and they use it to produce today schedule
                    'then just add TimeSpareFromYesterday to CountWorkingTimeToNow

                    For i As Integer = 0 To record.Volumn - 1 'this starts from 0
                        LstItem.Add(New Item(record.Model, record.Duration, record.TimeToChange))
                    Next
                End If

                firstRecord = False

            Else
                For i As Integer = 0 To record.Volumn - 1
                    LstItem.Add(New Item(record.Model, record.Duration, record.TimeToChange))
                Next
            End If
            

            '-----20141129 - Add condition-----
            If record.TimeToChange > 0 Then
                LstItem.Add(New Item("change", record.TimeToChange, record.TimeToChange))
            End If
            '-----END 20141129-----


        Next

        '-----20141129 - Add condition-----
        If LstItem.Count > 0 AndAlso LstItem(LstItem.Count - 1).Model.Equals("change") Then
            LstItem.RemoveAt(LstItem.Count - 1)
        End If
        '-----END 20141129-----


    End Sub

    Public Sub SetLblTarget()
        'Dim totalUnit As Integer = CountTarget()

        'Dim noOfChange = LstItem.FindAll(Function(p) p.Model.Equals("change")).Count
        'Dim totalUnit As Integer = LstItem.Count - noOfChange

        Dim noOfChange = LstTargetToday.FindAll(Function(p) p.Model.Equals("change")).Count
        Dim totalUnit As Integer = LstTargetToday.Count - noOfChange
        Dim s As String
        If TimeSpareFromYesterday < 0 Then totalUnit -= 1
        's = "Today Target: " + totalUnit.ToString() + " units"
        s = totalUnit.ToString()
        lblTarget.Text = s
    End Sub

    Public Sub SetInitLabel()
        Dim now As DateTime = DateTime.Now
        lblTime.Text = now.ToString("HH:mm")
        lblShop.Text = ShopName
        'pnl_shopname.Width = lblShop.Width + 10
        lblStatus.Text = Status
        lblDate.Text = Today
        SetLblTarget()
        lblPlan.Text = Plan.ToString()
        lblActual.Text = Actual.ToString()
        lblDiff.Text = Diff.ToString()
    End Sub

    Public Sub GetTimerFile()
        Try
            Using sr As New StreamReader("timer.txt")
                Dim line As String

                line = sr.ReadLine()
                TimeSche.MorStart = line
                line = sr.ReadLine()
                TimeSche.MorBreakStart = line
                line = sr.ReadLine()
                TimeSche.MorBreakEnd = line
                line = sr.ReadLine()
                TimeSche.LunchStart = line
                line = sr.ReadLine()
                TimeSche.LunchEnd = line
                line = sr.ReadLine()
                TimeSche.NoonStart = line
                line = sr.ReadLine()
                TimeSche.NoonBreakStart = line
                line = sr.ReadLine()
                TimeSche.NoonBreakEnd = line
                line = sr.ReadLine()
                TimeSche.NoonEnd = line

                If sr.Peek() <> -1 Then
                    line = sr.ReadLine()
                    TimeSche.OTStart = line
                    line = sr.ReadLine()
                    TimeSche.OTEnd = line
                End If
            End Using
        Catch e As Exception
            'MessageBox.Show("Invalid file timer.txt!")
            WriteToLog("Invalid file timer.txt!")
        End Try
    End Sub

    Public Function ConvertTimeToString(ByVal time As DateTime) As String
        Dim s As String
        Dim hour As String
        Dim min As String

        hour = time.Hour.ToString()
        If hour.Length = 1 Then
            hour = "0" + hour
        End If

        min = time.Minute.ToString()
        If min.Length = 1 Then
            min = "0" + min
        End If

        s = hour + ":" + min
        Return s
    End Function

    Public Function GetStatus() As String
        Dim line As String = ""
        Try
            Using sr As New StreamReader("status.txt")
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                End While
            End Using
        Catch e As Exception
            'MessageBox.Show("Cannot get status!")
            WriteToLog("Cannot get status!")
        End Try
        Return line
    End Function

    Public Sub SaveStatus(ByVal stt As String)
        Try
            Dim file As New StreamWriter("status.txt")
            file.WriteLine(stt)
            file.Close()
        Catch e As Exception
            'MessageBox.Show("'status.txt' could not be read!")
            WriteToLog("'status.txt' could not be read!")
        End Try
    End Sub

    Public Function GetLastModelAndTime() As String
        Dim line As String = ""
        Try
            Using sr As New StreamReader("lastmodel.txt")
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                End While
            End Using
        Catch e As Exception
            'MessageBox.Show("Cannot get status!")
            WriteToLog("Cannot get last model!")
        End Try
        Return line
    End Function

    Public Sub SaveLastModel(ByVal lastModel As String, ByVal acTime As Integer)
        Try
            Dim file As New StreamWriter("lastmodel.txt")
            file.WriteLine(lastModel & "|" & acTime)
            file.Close()
        Catch e As Exception
            'MessageBox.Show("'status.txt' could not be read!")
            WriteToLog("'lastmodel.txt' could not be read!")
        End Try
    End Sub

    Public Sub AddPendingToLstItem()

        Try

            'add on Jan 21 -----
            'if pending is present but somehow targettoday was not created
            'then delete the pending, consider new date
            If Not File.Exists("targettoday.txt") Then
                File.Delete("pending.txt")
                IsNewDate = True
                Exit Sub
            End If
            '---end Jan21----


            Using sr As New StreamReader("pending.txt")
                Dim dateInFile As String = sr.ReadLine()
                Dim today As String = DateTime.Now.ToString("MM/dd/yyyy")
                If today.Equals(dateInFile) Then
                    IsNewDate = False
                Else
                    IsNewDate = True
                    If Not GetPendingPrevDay Then
                        Exit Sub
                    End If

                End If

                Dim line As String
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                    Dim split As String() = line.Split("|")

                    '-----20141203 Edit - add condition-----
                    Dim note As String = split(3)
                    'if note = X, this item hasnot been done yet
                    If note.Equals("X") Then
                        Dim mo As String = split(0)
                        Dim du As String = split(1)
                        Dim ttc As String = split(2)
                        Dim iDu As Integer = Integer.Parse(du)
                        Dim iTtc As Integer = Integer.Parse(ttc)
                        Dim item As Item = New Item(mo, iDu, iTtc)
                        LstItem.Add(item)
                    End If
                    '-----END 20141203 Edit-----

                End While
            End Using
        Catch e As Exception
            'MessageBox.Show("'pending.txt' could not be read!")
            WriteToLog("'pending.txt' could not be read!")
        End Try
    End Sub

    '-----20141203 Add-----
    'call this method when starting app after power-off (not at begining day)
    Public Sub AddPendingToLstActual()
        Try
            Using sr As New StreamReader("pending.txt")
                Dim dateInFile As String = sr.ReadLine()
                'Dim today As String = DateTime.Now.ToString("MM/dd/yyyy")
                'If today.Equals(dateInFile) Then
                '    IsNewDate = False
                'Else
                '    IsNewDate = True
                'End If

                Dim line As String
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                    Dim split As String() = line.Split("|")

                    Dim mo As String = split(0)
                    Dim du As String = split(1)
                    Dim ttc As String = split(2)
                    Dim stt As String = split(3)
                    Dim iDu As Integer = Integer.Parse(du)
                    Dim iTtc As Integer = Integer.Parse(ttc)
                    Dim item As ActualItem = New ActualItem(mo, iDu, iTtc, stt)
                    LstActualItem.Add(item)

                End While
            End Using
        Catch e As Exception
            'MessageBox.Show("'pending.txt' could not be read!")
            WriteToLog("'pending.txt' could not be read to add to LstActualItem!")
        End Try
    End Sub
    '-----END 20141203 Add-----

    Public Sub SavePendingFile()
        Try
            Dim file As New StreamWriter("pending.txt")
            file.WriteLine(DateTime.Now.ToString("MM/dd/yyyy"))

            '-----20141203 Delete-----
            'For Each item As Item In LstItem
            '    file.WriteLine(item.Model + "|" + item.Duration.ToString() + "|" + item.TimeToChange.ToString())
            'Next
            '-----END 20141203 Delete-----

            '-----20141203 Add-----
            For Each item As ActualItem In LstActualItem
                file.WriteLine(item.Model + "|" + item.Duration.ToString() + "|" + item.TimeToChange.ToString() + "|" + item.Status)
            Next
            '-----END 20141203 Add-----


            file.Close()
        Catch e As Exception
            'MessageBox.Show("'pending.txt' could not be editted!")
            WriteToLog("'pending.txt' could not be editted!")
        End Try
    End Sub

    Public Function CountTimeSpan(ByVal startT As String, ByVal endT As String) As Integer
        Dim time As Integer = 0
        Dim starTime As DateTime = DateTime.ParseExact(startT, "HH:mm", Nothing)
        Dim endTime As DateTime = DateTime.ParseExact(endT, "HH:mm", Nothing)
        Dim timeSpan As TimeSpan = endTime - starTime
        time = CInt(timeSpan.TotalMinutes)
        Return time
    End Function

    Public Function CountWorkingTimeTo(ByVal thisTime As String) As Integer
        'count working time from beginning to thisTime (HH:mm)
        Dim workingTime As Integer = 0
        Dim now As String = thisTime 'DateTime.Now.ToString("HH:mm")

        'If now.CompareTo(TimeSche.MorStart) < 0 Then
        '    workingTime = CountTimeSpan(now, TimeSche.MorStart)
        'Else
        If now.CompareTo(TimeSche.MorBreakStart) < 0 Then
            workingTime = CountTimeSpan(TimeSche.MorStart, now)
        Else
            If now.CompareTo(TimeSche.MorBreakEnd) < 0 Then
                workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart)
            Else
                If now.CompareTo(TimeSche.LunchStart) < 0 Then
                    workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                        + CountTimeSpan(TimeSche.MorBreakEnd, now)
                Else
                    If now.CompareTo(TimeSche.NoonStart) < 0 Then
                        workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                            + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart)
                    Else
                        If now.CompareTo(TimeSche.NoonBreakStart) < 0 Then
                            workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                + CountTimeSpan(TimeSche.NoonStart, now)
                        Else
                            If now.CompareTo(TimeSche.NoonBreakEnd) < 0 Then
                                workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                    + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                    + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart)
                            Else
                                If now.CompareTo(TimeSche.NoonEnd) < 0 Then
                                    workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                        + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                        + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                        + CountTimeSpan(TimeSche.NoonBreakEnd, now)
                                Else
                                    'if not OT
                                    If TimeSche.OTStart.Length = 0 Then
                                        workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                            + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                            + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                            + CountTimeSpan(TimeSche.NoonBreakEnd, TimeSche.NoonEnd)
                                    Else
                                        'if OT
                                        If now.CompareTo(TimeSche.OTStart) < 0 Then
                                            workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                                + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                                + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                                + CountTimeSpan(TimeSche.NoonBreakEnd, TimeSche.NoonEnd)
                                        Else
                                            If now.CompareTo(TimeSche.OTEnd) < 0 Then
                                                workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                                    + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                                    + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                                    + CountTimeSpan(TimeSche.NoonBreakEnd, TimeSche.NoonEnd) _
                                                    + CountTimeSpan(TimeSche.OTStart, now)
                                            Else
                                                workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                                    + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                                    + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                                    + CountTimeSpan(TimeSche.NoonBreakEnd, TimeSche.NoonEnd) _
                                                    + CountTimeSpan(TimeSche.OTStart, TimeSche.OTEnd)
                                            End If
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
        'End If




        Return workingTime
    End Function

    Public Function GetStatusNow() As String
        'Dim workingTime As Integer = 0
        Dim stt As String = ""
        Dim now As String = DateTime.Now.ToString("HH:mm")

        If now.CompareTo(TimeSche.MorStart) < 0 Then
            stt = ""
        Else
            If now.CompareTo(TimeSche.MorBreakStart) < 0 Then
                stt = "MorStart"
            Else
                If now.CompareTo(TimeSche.MorBreakEnd) < 0 Then
                    stt = "MorBreakStart"
                Else
                    If now.CompareTo(TimeSche.LunchStart) < 0 Then
                        stt = "MorBreakEnd"
                    Else
                        If now.CompareTo(TimeSche.LunchEnd) < 0 Then
                            stt = "LunchStart"
                        Else
                            If now.CompareTo(TimeSche.NoonStart) < 0 Then
                                stt = "LunchEnd"
                            Else
                                If now.CompareTo(TimeSche.NoonBreakStart) < 0 Then
                                    stt = "NoonStart"
                                Else
                                    If now.CompareTo(TimeSche.NoonBreakEnd) < 0 Then
                                        stt = "NoonBreakStart"
                                    Else
                                        If now.CompareTo(TimeSche.NoonEnd) < 0 Then
                                            stt = "NoonBreakEnd"
                                        Else
                                            'if not OT
                                            If TimeSche.OTStart.Length = 0 Then
                                                stt = "NoonEnd"
                                            Else
                                                'if OT
                                                If now.CompareTo(TimeSche.OTStart) < 0 Then
                                                    stt = "NoonEnd"
                                                Else
                                                    If now.CompareTo(TimeSche.OTEnd) < 0 Then
                                                        stt = "OTStart"
                                                    Else
                                                        stt = "OTEnd"
                                                    End If
                                                End If
                                            End If
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If




        Return stt
    End Function

    Public Function CountPlan() As Integer
        Dim workingTime As Integer = CountWorkingTimeTo(Now.ToString("HH:mm"))
        If TimeSpareFromYesterday > 0 Then workingTime += TimeSpareFromYesterday

        If workingTime <= 0 Then
            Return 0
        End If

        Dim planAtNow As Integer = 0
        For Each item As Item In LstTargetToday
            If workingTime > 0 Then
                workingTime -= item.Duration
                If (Not item.Model.Equals("change")) AndAlso workingTime >= 0 Then
                    planAtNow += 1
                End If
            End If
        Next

        Return planAtNow
    End Function

    Public Sub UpdateLstItemAfterCountingPlan()
        '-----20141127-----
        'update list item
        Dim wTime As Integer = CountWorkingTimeTo(Now.ToString("HH:mm"))
        If TimeSpareFromYesterday > 0 Then wTime += TimeSpareFromYesterday

        While wTime > 0 AndAlso LstItem.Count > 0
            LstItem(0).Duration -= 1
            If LstItem(0).Duration = 0 Then
                LstItem.RemoveAt(0)
            End If
            wTime -= 1
        End While
        '-----END 20141127-----
    End Sub

    'call this method when starting app after power-off (not at begining day)
    'this file is created at begining day
    Public Sub AddTargetFromFileToLstTarget()
        Try
            Using sr As New StreamReader("targettoday.txt")
                Dim dateInFile As String = sr.ReadLine()
                Dim today As String = DateTime.Now.ToString("MM/dd/yyyy")
                If today.Equals(dateInFile) Then
                    Dim line As String
                    While sr.Peek() <> -1
                        line = sr.ReadLine()
                        Dim split As String() = line.Split("|")
                        Dim mo As String = split(0)
                        Dim du As String = split(1)
                        Dim ttc As String = split(2)
                        Dim iDu As Integer = Integer.Parse(du)
                        Dim iTtc As Integer = Integer.Parse(ttc)
                        Dim item As Item = New Item(mo, iDu, iTtc)
                        LstTargetToday.Add(item)
                    End While
                End If
            End Using
        Catch e As Exception
            'MessageBox.Show("'targettoday.txt' could not be read!")
            WriteToLog("'targettoday.txt' could not be read!")
        End Try
    End Sub

    'at begining day, call this method to save target today in case power-off
    Public Sub SaveTargetToday()
        Dim path As String = "targettoday.txt"
        Try
            Dim file As New StreamWriter(path)
            file.WriteLine(DateTime.Now.ToString("MM/dd/yyyy"))
            For Each item As Item In LstItem
                file.WriteLine(item.Model + "|" + item.Duration.ToString() + "|" + item.TimeToChange.ToString())
                '-----20141127-----
                'add item to list target to count today's target
                LstTargetToday.Add(item)
                '-----END 20141127-----
            Next
            file.Close()
        Catch e As Exception
            'MessageBox.Show("'targettoday.txt' could not be editted!")
            WriteToLog("'targettoday.txt' could not be editted!")
        End Try
    End Sub

    'Update working hour
    'Host: 		WORK|07:30|...
    Public Sub SaveWorkMsg(ByVal msg As String)
        Dim path As String = "timer.txt"
        Try
            Dim file As New StreamWriter(path)

            'remove title of msg (5 first letters)
            msg = msg.Substring(5)
            Dim split As String() = msg.Split("|")

            For Each s As String In split
                file.WriteLine(s)
            Next

            file.Close()

            GetTimerFile()

            '-----20141130 - Add-----
            Status = GetStatusNow()
            Plan = CountPlan()
            UpdateLstItemAfterCountingPlan()
            lblPlan.Text = Plan
            lblActual.Text = Actual
            lblDiff.Text = Actual - Plan
            '-----END20141130 - Add-----
        Catch e As Exception
            'MessageBox.Show("Cannot save working time!")
            WriteToLog("Cannot save working time!")
        End Try
    End Sub

    'Update Schedule
    'Host:		SCHE|MMddyyyy|Model1|qty|changeTime|duration|Model2|...
    Public Sub SaveScheMsg(ByVal msg As String)
        'remove title of msg (5 first letters)
        msg = msg.Substring(5)

        Dim strDate As String = msg.Substring(0, 8)
        strDate = strDate.Substring(4, 4) & strDate.Substring(0, 4) 'swap year to the beginning now yyyyMMdd
        Dim path As String = "schedule\schedule_" + strDate + ".txt"
        Try
            Dim file As New StreamWriter(path)

            file.WriteLine(strDate.Substring(4, 2) & "/" & strDate.Substring(6, 2) & "/" & strDate.Substring(0, 4))

            'remove date of msg (9 first letters)
            msg = msg.Substring(9)

            Dim split As String() = msg.Split("|")

            Dim record As String = ""

            'record = Model1|qty|changeTime|duration
            For i As Integer = 0 To split.Length - 1
                record = record & split(i) & "|"
                If i Mod 4 = 3 Then
                    record = record.Remove(record.Length - 1)
                    file.WriteLine(record)
                    record = ""
                End If
            Next

            file.Close()

            ResetAfterUpdatingSchedule()
        Catch e As Exception
            'MessageBox.Show("Cannot update schedule!")
            WriteToLog("Cannot update schedule!")
        End Try
    End Sub

    'Ask Schedule
    'Host		ASKS|MMddyyyy
    'Client		ShopCode|MMddyyyy|Model1|qty|changeTime|duration|Model2|...
    Public Function ReplyAskSchedule(ByVal msg As String) As String
        Dim reply As String = ShopCode & "|ASKS|"
        Dim strDate As String = msg.Substring(5)
        Dim path As String = "schedule\schedule_" + strDate + ".txt"
        reply = reply & strDate & "|"
        Try
            Using sr As New StreamReader(path)
                Dim line As String
                'the 1st line is MM/dd/yyyy => do nothing
                line = sr.ReadLine()
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                    reply = reply & line & "|"
                End While
                reply = reply.Remove(reply.Length - 1)
            End Using
        Catch e As Exception
            'MessageBox.Show("Cannot reply schedule!")
            WriteToLog("Cannot reply schedule!")
        End Try

        Return reply
    End Function

    Public Sub ResetAfterUpdatingSchedule()
        LstItem.Clear()
        LstRecord.Clear()
        LstTargetToday.Clear()

        GetSchedule()
        AddScheduleToLstItem()
        SaveTargetToday()

        '-----20141128-----
        SetLblTarget()
        '-----END 20141128-----

        'AddTargetFromFileToLstTarget()

        GetTimerFile()
        Status = GetStatusNow()

        Plan = CountPlan()
        Diff = Actual - Plan
        SaveNumberFile()

        '-----20141128-----
        UpdateLstItemAfterCountingPlan()
        '-----END 20141128-----

        SetInitLabel()
        WriteLstItem()
        WriteLstTarget()
    End Sub

    Public Sub DoWork()
        If LstItem.Count = 0 Then Exit Sub

        LstItem(0).Duration -= 1

        If LstItem(0).Duration <= 0 Then
            'if model = change, do nothing
            'if model != change, update number
            If Not LstItem(0).Model.Equals("change") Then
                'LstItem.RemoveAt(0)
                Plan += 1
                My.Computer.Audio.Play("ding.wav", AudioPlayMode.Background)

                Diff = Actual - Plan
                lblPlan.Text = Plan.ToString()
                lblDiff.Text = Diff.ToString()
                SaveNumberFile()

                '-----20141130-----
                If ActivelySend Then
                    'send msg to host
                    CountTimesSendingMsg = 0
                    TimerSendMsg.Enabled = True
                    TimerSendMsg_Tick(TimerSendMsg, New EventArgs)
                End If
                '-----END 20141130-----
            End If

            '-----20141127-----
            LstItem.RemoveAt(0)
            '-----END 20141127-----
        End If

        '-----20141127 for debug-----
        WriteLstItem()
        '-----END 20141127-----
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        lblTime.Text = DateTime.Now.ToString("HH:mm")
        Dim stNow As String = ConvertTimeToString(DateTime.Now)
        Dim sec As Integer = Now.Second

        Select Case Status
            Case ""
                If stNow.Equals(TimeSche.MorStart) Then
                    Status = "MorStart"
                    SaveStatus("MorStart")
                    'begin counting actual time
                    TimerActual.Enabled = True
                End If

            Case "MorStart"
                If sec < 5 Then DoWork() 'only DoWork once/min
                If stNow.Equals(TimeSche.MorBreakStart) Then
                    Status = "MorBreakStart"
                    SaveStatus("MorBreakStart")
                End If

            Case "MorBreakStart"
                If stNow.Equals(TimeSche.MorBreakEnd) Then
                    Status = "MorBreakEnd"
                    SaveStatus("MorBreakEnd")
                End If

            Case "MorBreakEnd"
                If sec < 5 Then DoWork() 'only DoWork once/min
                If stNow.Equals(TimeSche.LunchStart) Then
                    Status = "LunchStart"
                    SaveStatus("LunchStart")
                End If

            Case "LunchStart"
                If stNow.Equals(TimeSche.LunchEnd) Then
                    Status = "LunchEnd"
                    SaveStatus("LunchEnd")
                End If

            Case "LunchEnd"
                If stNow.Equals(TimeSche.NoonStart) Then
                    Status = "NoonStart"
                    SaveStatus("NoonStart")
                End If

            Case "NoonStart"
                If sec < 5 Then DoWork() 'only DoWork once/min
                If stNow.Equals(TimeSche.NoonBreakStart) Then
                    Status = "NoonBreakStart"
                    SaveStatus("NoonBreakStart")
                End If

            Case "NoonBreakStart"
                If stNow.Equals(TimeSche.NoonBreakEnd) Then
                    Status = "NoonBreakEnd"
                    SaveStatus("NoonBreakEnd")
                End If

            Case "NoonBreakEnd"
                If sec < 5 Then DoWork() 'only DoWork once/min
                If stNow.Equals(TimeSche.NoonEnd) Then
                    Status = "NoonEnd"
                    SaveStatus("NoonEnd")
                End If

            Case "NoonEnd"
                If TimeSche.OTStart.Length > 0 Then
                    If stNow.Equals(TimeSche.OTStart) Then
                        Status = "OTStart"
                        SaveStatus("OTStart")
                    End If
                End If

            Case "OTStart"
                If TimeSche.OTEnd.Length > 0 Then
                    If sec < 5 Then DoWork() 'only DoWork once/min
                    If stNow.Equals(TimeSche.OTEnd) Then
                        Status = "OTEnd"
                        SaveStatus("OTEnd")
                    End If
                End If

            Case Else

        End Select

        lblStatus.Text = Status

        If sec < 5 Then
            If CountWorkingTimeTo(Now.ToString("HH:mm")) > 0 Then
                SavePendingFile()
            End If

            'check if no connection then should connect
            If Not Tcp.isConnected Then
                ConnetTCP()
            End If
        End If
    End Sub

    Private Sub btnDone_Click(sender As Object, e As EventArgs) Handles btnDone.Click
        Actual += 1
        Diff = Actual - Plan
        lblActual.Text = Actual.ToString()
        lblDiff.Text = Diff.ToString()

        If Diff < 0 Then
            pnl_diff.BackColor = Color.Red
            panelDiff.BackColor = Color.Red
        Else
            pnl_diff.BackColor = Color.Silver
            panelDiff.BackColor = Color.Silver
        End If

        SaveNumberFile()

        'send msg to host
        CountTimesSendingMsg = 0
        TimerSendMsg.Enabled = True

    End Sub

    Private Sub btn_minus_Click(sender As Object, e As EventArgs) Handles btn_minus.Click
        Actual -= 1
        Diff = Actual - Plan
        lblActual.Text = Actual.ToString()
        lblDiff.Text = Diff.ToString()

        If Diff < 0 Then
            pnl_diff.BackColor = Color.Red
            panelDiff.BackColor = Color.Red
        Else
            pnl_diff.BackColor = Color.Silver
            panelDiff.BackColor = Color.Silver
        End If

        SaveNumberFile()

        'send msg to host
        CountTimesSendingMsg = 0
        TimerSendMsg.Enabled = True

    End Sub

    Public Sub SendMsgToHost()
        Dim msg As String
        'ShopCode|PROD|Plan|Actual
        msg = ShopCode & "|PROD|" & Plan.ToString() & "|" & Actual.ToString()
        Tcp.SendData(msg, RemoteAddr, RemotePort)
    End Sub

    Private Sub TimerSendMsg_Tick(sender As Object, e As EventArgs) Handles TimerSendMsg.Tick
        'Dim lastModelAndTime = GetLastModelAndTime()

        If CountTimesSendingMsg < nRetries Then
            SendMsgToHost()
            CountTimesSendingMsg += 1
        End If
    End Sub

    Public Sub ConnetTCP()

        'Dim strHostName As String = Dns.GetHostName()
        'Dim ipEntry As IPHostEntry = Dns.GetHostEntry(strHostName)
        'HostAddr = ipEntry.AddressList(0).ToString()
        'HostAddr = "192.168.1.111"
        'HostPort = 5000
        'MessageBox.Show("My IP=" & HostAddr)
        Tcp.connect(HostAddr, HostPort)
    End Sub

    'handle receiving msg from host
    Public Sub myChat_Datareceived(txt As String) Handles Tcp.Datareceived
        'lbout.Items.Add(Now & " >>In >> " & txt)
        'MessageBox.Show(txt)

        If txt.Length >= 4 Then
            Dim reply As String = ""
            Dim title As String = txt.Substring(0, 4)

            Select Case title
                Case "WORK"
                    SaveWorkMsg(txt)
                    reply = ShopCode & "|WORK"
                Case "SCHE"
                    SaveScheMsg(txt)
                    reply = ShopCode & "|SCHE"
                Case "ASKS"
                    reply = ReplyAskSchedule(txt)
                Case "ONLN"
                    reply = ShopCode & "|ONLN"
                Case "PROD"
                    reply = ShopCode & "|PROD|" & Plan.ToString() & "|" & Actual.ToString()
                Case Else

            End Select

            Tcp.SendData(reply, RemoteAddr, RemotePort)
        Else
            'when host received msg from this sshop
            If txt.Equals("OK") Then
                TimerSendMsg.Enabled = False
                TimerSendMsg.Stop()
            End If
        End If

    End Sub


    Private Sub connection(ByVal status As Boolean) Handles Tcp.connection
        If status Then
            StatusLabel_adapter.Image = My.Resources.ledCornerGreen
            StatusLabel_receive.Image = My.Resources.ledCornerOrange
        Else
            StatusLabel_adapter.Image = My.Resources.ledCornerGray
            StatusLabel_receive.Image = My.Resources.ledCornerGray
            StatusLabel_send.Image = My.Resources.ledCornerGray
        End If
    End Sub

    Private Sub rdata(ByVal receiveStatus As Boolean) Handles Tcp.recOK
        Try
            If receiveStatus Then
                StatusLabel_receive.Image = My.Resources.ledCornerGreen
                'StatusLabel_adapter.Text = "local " & Tcp.Local.ToString & _
                '                           " remote" & Tcp.Remote.ToString

            Else
                StatusLabel_receive.Image = My.Resources.ledCornerRed
            End If
        Catch ex As Exception
            'do nothing
        End Try

    End Sub

    Private Sub sendata(ByVal sendStatus As Boolean) Handles Tcp.sendOK
        Try
            If sendStatus Then
                StatusLabel_send.Image = My.Resources.ledCornerGreen
            Else
                StatusLabel_send.Image = My.Resources.ledCornerRed
            End If
        Catch ex As Exception
            'do nothing
        End Try
    End Sub

    Public Sub WriteToLog(txt As String)
        Dim fW As StreamWriter = New StreamWriter(LogFile, True)
        fW.WriteLine(Now & "   " & txt)
        fW.Close()
    End Sub

    Public Function GetCurrentDir() As String
        Return System.IO.Path.GetDirectoryName( _
            System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Replace("file:\", "")
    End Function

    Public Function ConvertFileNameToDate(ByVal fileName As String)
        'schedule_11202014.txt
        fileName = fileName.Substring(9, 8)
        'Dim da As DateTime = DateTime.ParseExact(fileName, "MMddyyyy", Nothing)
        'Return da.ToString("yyyyMMdd")
        Return fileName
    End Function

    Public Sub DeteleAllOldFiles()
        Dim today As String = DateTime.Now.ToString("yyyyMMdd")

        Dim di As New DirectoryInfo("schedule\")
        Dim diar1 As FileInfo()

        diar1 = di.GetFiles
        Dim fileDate As String

        For Each d In diar1
            fileDate = ConvertFileNameToDate(d.Name)
            If fileDate.CompareTo(today) < 0 Then
                Try
                    d.Delete()
                Catch ex As Exception
                    WriteToLog("Couldn't delete file " & fileDate)
                End Try

            End If
        Next
    End Sub

    Public Sub CloneLstTargetToLstActualItem()
        LstActualItem.Clear()
        For Each item As Item In LstTargetToday
            LstActualItem.Add(New ActualItem(item.Model, item.Duration, item.TimeToChange, "X"))
        Next
        'X: not be done yet
        'O: done
    End Sub

    '-----20141127-----
    'call this method when starting app after power-off (not at begining day)
    Public Sub CloneLstTargetToLstItem()
        LstItem.Clear()
        For Each item As Item In LstTargetToday
            LstItem.Add(New Item(item.Model, item.Duration, item.TimeToChange))
        Next
    End Sub
    '-----END 20141127-----

    Private Sub TimerActual_Tick(sender As Object, e As EventArgs) Handles TimerActual.Tick
        'If LstActualItem.Count > 0 Then
        '    If Not LstActualItem(0).Model.Equals("change") Then
        '        ActualTime += 1
        '        SaveLastModel(LstActualItem(0).Model, ActualTime)
        '    End If
        'End If
    End Sub

    Private Sub lblPlan_SizeChanged(sender As Object, e As EventArgs) Handles lblPlan.SizeChanged
        lblPlan.Left = (panelPlan.Width - lblPlan.Width) / 2
    End Sub

    Private Sub lblActual_MouseDown(sender As Object, e As MouseEventArgs) Handles lblActual.MouseDown
        If (Now.Subtract(prevClick).TotalSeconds < 1) Then
            If DebugMode = 1 Then MessageBox.Show("2 click within less than 1s")
            prevClick = Now
            Exit Sub
        End If

        prevClick = Now

        If e.Button = Windows.Forms.MouseButtons.Right Then
            '-----20141207 Delete by Dung-----
            'AddActual(-1)
            '-----20141207 END-----
        Else
            AddActual(+1)
        End If
    End Sub

    Private Sub AddActual(d As Integer)
        'd can be +1 or -1
        If d < 0 Then
            If Actual = 0 Then Exit Sub
        End If

        Actual += d
        Diff = Actual - Plan
        lblActual.Text = Actual.ToString()
        lblDiff.Text = Diff.ToString()

        SaveNumberFile()

        '-----20141203 Add-----
        If d > 0 Then
            'when a model has just been done, change stt of next item - the 1st item which has status = X
            Dim keepreading As Boolean = True
            For i As Integer = 0 To LstActualItem.Count - 1
                If keepreading = True Then
                    If LstActualItem(i).Status.Equals("X") Then
                        LstActualItem(i).Status = "O"

                        'check whether next item being "change", remove it
                        If i < LstActualItem.Count - 1 Then
                            If LstActualItem(i + 1).Model.Equals("change") Then
                                LstActualItem(i + 1).Status = "O"
                            End If
                        End If

                        keepreading = False

                        '-----20141207 Add by Dung-----
                        'check if previous item is "change"
                        If (i > 0) AndAlso (LstActualItem(i - 1).Model.Equals("change")) Then
                            SaveProdFile(LstActualItem(i).Model, LstActualItem(i - 1).TimeToChange)
                        Else
                            SaveProdFile(LstActualItem(i).Model, 0)
                        End If
                        '-----20141207 END-----
                    End If
                End If
            Next
        Else
            'd < 0
            'change stt of the last item which has status = O to status = X
            Dim keepreading As Boolean = True
            For i As Integer = 0 To LstActualItem.Count - 1
                If keepreading = True Then
                    If LstActualItem(i).Status.Equals("X") Then
                        If Not LstActualItem(i - 1).Model.Equals("change") Then
                            LstActualItem(i - 1).Status = "X"
                        Else
                            LstActualItem(i - 1).Status = "X"
                            LstActualItem(i - 2).Status = "X"
                        End If

                        keepreading = False
                    End If
                End If
            Next

            'if all item in LstActualItem have been done <=> there is no status X
            If keepreading = True Then
                LstActualItem(LstActualItem.Count - 1).Status = "X"
            End If

        End If

        'save to pending file
        SavePendingFile()

        WriteLstActual()
        '-----END 20141203 Add-----

        If ActivelySend Then
            'send msg to host
            CountTimesSendingMsg = 0
            TimerSendMsg.Enabled = True
            TimerSendMsg_Tick(TimerSendMsg, New EventArgs)
        End If

    End Sub

    Private Sub SaveProdFile(model As String, changeTime As Integer)
        '1st line: date (MM/dd/yyyy)
        'n+1 line: model|moveout_time|proc_time
        Dim fR As StreamReader = New StreamReader("production.txt")
        Dim st As String = ""
        Dim moveIn As String = ""
        Dim moveOut As String = Now.ToString("HH:mm")
        Dim pt As Integer
        fR.ReadLine() 'skip 1st line

        While fR.Peek <> -1
            st = fR.ReadLine()
        End While

        If st = "" Then 'this is 1st truck
            moveIn = TimeSche.MorStart
        Else
            moveIn = st.Split("|")(1)
        End If
        fR.Close()

        pt = ProcTime(moveIn, moveOut) - changeTime

        Dim fW As StreamWriter = New StreamWriter("production.txt", True)
        fW.WriteLine(model & "|" & moveOut & "|" & pt)
        fW.Close()
    End Sub

    Private Function ProcTime(moveIn As String, moveOut As String) As Integer
        Return CountWorkingTimeTo(moveOut) - CountWorkingTimeTo(moveIn)
    End Function

    Private Sub lblActual_SizeChanged(sender As Object, e As EventArgs) Handles lblActual.SizeChanged
        lblActual.Left = (panelActual.Width - lblActual.Width) / 2
    End Sub

    Private Sub lblDiff_SizeChanged(sender As Object, e As EventArgs) Handles lblDiff.SizeChanged
        lblDiff.Left = (panelDiff.Width - lblDiff.Width) / 2
    End Sub

    Private Sub lblDiff_TextChanged(sender As Object, e As EventArgs) Handles lblDiff.TextChanged
        If Diff < 0 Then
            pnl_diff.BackColor = Color.Red
            panelDiff.BackColor = Color.Red
        Else
            pnl_diff.BackColor = Color.Silver
            panelDiff.BackColor = Color.Silver
        End If
    End Sub

    Private Sub Label5_DoubleClick(sender As Object, e As EventArgs) Handles Label5.DoubleClick
        Me.WindowState = FormWindowState.Minimized
    End Sub

    '-----20141127 for debug-----
    Public Sub WriteLstItem()
        Dim s As String = "List Item" & vbNewLine & "Model|Duration|Time to change" & vbNewLine
        For Each i As Item In LstItem
            s = s & i.Model & "|" & i.Duration & "|" & i.TimeToChange & vbNewLine
        Next
        RichTextBox1.Text = s
    End Sub

    Public Sub WriteLstTarget()
        Dim s As String = "List Target" & vbNewLine & "Model|Duration|Time to change" & vbNewLine
        For Each i As Item In LstTargetToday
            s = s & i.Model & "|" & i.Duration & "|" & i.TimeToChange & vbNewLine
        Next
        RichTextBox2.Text = s
    End Sub
    '-----END 20141127 for debug-----

    '-----20141203 for debug-----
    Public Sub WriteLstActual()
        Dim s As String = "List Actual" & vbNewLine & "Model|Duration|Time to change|Status" & vbNewLine
        For Each i As ActualItem In LstActualItem
            s = s & i.Model & "|" & i.Duration & "|" & i.TimeToChange & "|" & i.Status & vbNewLine
        Next
        RichTextBox3.Text = s
    End Sub
    '-----END 20141203 for debug-----

End Class